<template>
  <el-row>
    <el-col :span="18">
      <el-breadcrumb class="app-breadcrumb" separator="/">
        <transition-group name="breadcrumb">
          <el-breadcrumb-item v-for="(item,index) in breadcrumbList" :key="index">
            <span v-if="index==breadcrumbList.length-1" class="no-redirect">{{ item.name }}</span>
            <a v-else @click.prevent="handlerLink(item)">{{ item.name }}</a>
          </el-breadcrumb-item>
        </transition-group>
      </el-breadcrumb>
    </el-col>
    <el-col :span="6" v-if="!isRoot && mediumtype == 'image'">
      <div align="right">
        <el-upload
                :action="uploadAction"
                multiple
                name="upfile"
                :data="uploadFormData"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :with-credentials="true"
        >
          <el-button type="primary" size="mini">
            <el-icon>
              <upload-filled />
            </el-icon>
            上传图片
          </el-button>
        </el-upload>
      </div>
    </el-col>
    <el-col :span="24" class="mt10">
      <el-table
              ref="storageTableRef"
              :data="tableData.listData"
              v-loading="isloading"
              border
              width="100%"
              max-height="380px"
              :row-class-name="tableRowClassName"
              @row-click="handleClickRow"
              @select="handleSelect"
              @select-all="handleSelectAll"
      >
        <el-table-column type="selection" width="50" :selectable="selectable" align="center" v-if="selectType == 'checkbox'" />
        <el-table-column v-else align="center" width="50">
          <template #default="{row, $index}">
            <span @click.stop>
              <el-radio
                      :disabled="isDisabled(row)"
                      v-model="selectedRadioIndex"
                      :label="$index"
                      @change="handleChangeRadio(row)"
              ><span></span></el-radio>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" :show-overflow-tooltip="true">
          <template #default="{row}">
            <a @click.prevent="handlerLink(row)" v-if="row.filetype == 0" href="" class="flex align-items">
              <el-icon>
                <folder />
              </el-icon>
              <span class="txttdellipsis">{{row.name}}</span>
            </a>
            <span v-else-if="row.filetype == 2" class="flex align-items">
                <span @click.stop>
                  <el-image
                          :preview-src-list="srcList"
                          :initial-index="initialIndex(row.fid)"
                          :src="getStorageImageUrl(row.fid, 2)"
                  />
                </span>
                <span class="txttdellipsis">{{row.name}}</span>
              </span>
            <a v-else-if="row.filetype == 7" class="flex align-items" href="javascript:;" @click.stop="handleVideoPlay(row)">
              <el-icon>
                <video-play />
              </el-icon>
              <span class="txttdellipsis">{{row.name}}</span>
            </a>
            <span v-else-if="row.filetype == 4"  class="">
              <audio-table-column
                :ref="el => { if (el) audioTableColumn[row.fid] = el }"
                :row="row"
                sourcefrom="storage"
                @handleAudioPlay="handleAudioPlay"
              />
              <!--<div class="flex align-items">
                <el-icon>
                  <headset />
                </el-icon>
                <span class="txttdellipsis">{{row.name}}</span>
              </div>
              <div>
                <audio-player :src="getVideoPlayUrl(row)" />
              </div>-->
            </span>
            <span class="flex align-items" v-else>
                  <el-icon>
                    <document />
                  </el-icon>
                  <span class="txttdellipsis">{{row.name}}</span>
              </span>
          </template>
        </el-table-column>
        <el-table-column label="FID" :show-overflow-tooltip="true" align="center">
          <template #default="{row}">
            <span v-if="row.fid" class="txttdellipsis">{{row.fid}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="100" align="center">
          <template #default="{row}">
            <span v-if="row.fsize > 0">{{formatSize(row.fsize)}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="ctime" />
      </el-table>
    </el-col>
    <el-col :span="24" class="mt10" v-if="!isRoot">
      <folder-pagination
              :queryList="queryList"
              :total="tableData.total"
              @pagination="getFolderFileList"
      />
    </el-col>
  </el-row>
</template>

<script>
  import {computed, reactive, ref, toRef, nextTick} from 'vue'
  import {useStore} from 'vuex'
  import {getSubRefGroup} from "@/api/group";
  import {getFolder} from "@/api/media/storage";
  import {formatSize, mimeTypeList, getStorageImageUrl, getVideoPlayUrl} from "@/utils/usage-config";
  import FolderPagination from "@/views/medium/storage/components/FolderPagination";
  import {ElMessage} from 'element-plus'
  import {
    getMediaReledImageFids,
    getSeriesReledImages,
    getMediaReledVideoFids,
    getSeriesReledVideoFids
  } from "@/api/media/media";
  import {getPackageReledFids, getPackageReledVideoFids} from "@/api/package/material";
  import AudioTableColumn from "@/components/Common/AudioTableColumn";

  export default {
    name: "StorageMedium",
    components: { FolderPagination, AudioTableColumn },
    props: {
      formData: {
        type: Object,
      },
      mediumtype: {
        type: String,
        default: 'image'
      },
      mediatype: {
        type: String,
        default: 'media'
      },
      relAction: {
        type: String,
        default: 'relmedium'
      },
      selectType: {
        type: String,
        default: 'checkbox'
      },
    },
    emits: ['handleVideoPlay'],
    setup(props, context) {
      const store = useStore()
      const relFormData = toRef(props, 'formData')
      const groupid_list = ref([])
      const rootQueryList = reactive({
        action: 'subiddir',
        admin: store.getters.subinfo.isadmin,
        groupid: '',
        type: 5
      })
      const isloading = ref(false)
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const breadcrumbList = ref([
        {
          pid: 0,
          path: '/',
          name: '根目录'
        }
      ])
      const queryList = reactive({
        path: '/',
        action: 'getlist',
        startnum: 1,
        pagenum: 25,
        type: 5,
        order: 2
      })
      const isRoot = ref(true)
      const srcList = ref([])
      const storageTableRef = ref(null)
      const uploadAction = ref(process.env.VUE_APP_BASE_MEDIA_API + '/console/cloudstorage/image/upload')
      const uploadFormData = reactive({
        path: '/'
      })
      const reledFids = ref([])
      const currentGroupid = ref(0)
      const selectedRadioIndex = ref(undefined)

      const initialIndex = computed(() => {
        return (fid) => {
          const index = srcList.value.findIndex(src => {
            return src.indexOf(fid) != -1
          })
          return index
        }
      })
      const isDisabled = computed(() => {
        return (row) => {
          if (props.mediumtype == 'image' && row.filetype == 2) {
            return false
          } else if (props.mediumtype == 'video' && row.filetype == 7) {
            return false
          } else if (props.mediumtype == 'audio' && row.filetype == 4) {
            return false
          } else {
            return true
          }
        }
      })

      /** 获取部门列表 **/
      const getGroupList = () => {
        getSubRefGroup().then(response => {
          response.data.forEach(group => {
            groupid_list.value.push(group.groupid)
            rootQueryList.groupid = groupid_list.value.join(',')
          })
        })
      }
      /** 获取根目录 **/
      const getRootFolderList = () => {
        isloading.value = true
        selectedRadioIndex.value = undefined
        getFolder(rootQueryList).then(response => {
          isloading.value = false
          tableData.listData = response.data
        })
      }
      /** 判断是否可选 **/
      const selectable = (row) => {
        if (reledFids.value.includes(row.fid)) {
          return false
        } else if (props.mediumtype == 'image') {
          if (row.filetype == 2) {
            return true
          } else {
            return false
          }
        } else if (props.mediumtype == 'video') {
          if (row.filetype == 7) {
            return true
          } else {
            return false
          }
        } else {
          if (row.filetype == 4) {
            return true
          } else {
            return false
          }
        }
      }
      /** 点击目录 **/
      const handlerLink = (item) => {
        if (item.groupid !== undefined) {
          currentGroupid.value = parseInt(item.groupid)
        }
        setBreadcrumb(item)
        queryList.startnum = 1
        queryList.path = getBreadcrumbPath()
        uploadFormData.path = getBreadcrumbPath()
        isRoot.value = breadcrumbList.value.length == 1
        if (isRoot.value) {
          getRootFolderList()
        } else {
          getFolderFileList()
        }
      }
      /** 设置面包屑导航 **/
      const setBreadcrumb = (item) => {
        const index = breadcrumbList.value.findIndex(b => b.pid === item.pid)
        const pathTotal = breadcrumbList.value.length
        if (index === -1) {
          breadcrumbList.value.push({
            pid: item.pid,
            path: item.name,
            name: item.name
          })
        } else {
          breadcrumbList.value.splice(index+1, (pathTotal-index+1))
        }
      }
      /** 获取面包屑导航路径 **/
      const getBreadcrumbPath = () => {
        let pathArr = []
        breadcrumbList.value.forEach(b => {
          pathArr.push(b.path)
        })
        return pathArr.join('/')
      }
      /** 获取目录下文件列表 **/
      const getFolderFileList = () => {
        relFormData.value.datas = []
        selectedRadioIndex.value = undefined
        isloading.value = true
        getFolder(queryList).then(response => {
          isloading.value = false
          tableData.total = response.totalnum
          tableData.listData = response.data
          nextTick(() => {
            tableData.listData.forEach(row => {
              if (row.filetype !== undefined && (row.filetype == 2 || row.filetype == 7 || row.filetype == 4)) {
                if (reledFids.value.includes(row.fid)) {
                  storageTableRef.value.toggleRowSelection(row, true)
                }
              }
              if (row.filetype !== undefined && row.filetype == 2) {
                srcList.value.push(getStorageImageUrl(row.fid, 1))
              }
            })
          })
        })
      }
      /** 点击单行 **/
      const handleClickRow = (row) => {
        if (!reledFids.value.includes(row.fid)) {
          if (props.mediumtype == 'image') {
            if (row.filetype == 2) {
              selectedRadioIndex.value = row.index
              handleSelectedImgIds(row)
            }
          } else {
            if (row.filetype == 7 || row.filetype == 4) {
              selectedRadioIndex.value = row.index
              handleSelectedVideos(row)
            }
          }
        }
      }
      /** 单选 **/
      const handleSelect = (selection, row) => {
        if (props.mediumtype == 'image') {
          if (row.filetype == 2) {
            handleSelectedImgIds(row)
          }
        } else {
          if (row.filetype == 7 || row.filetype == 4) {
            handleSelectedVideos(row)
          }
        }
      }
      /** 全选 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (props.mediumtype == 'image') {
              const index = relFormData.value.datas.findIndex(d => d.sourceid == row.fid)
              if (index == -1) {
                relFormData.value.datas.push(transferMedium(row))
              }
            } else {
              const index = relFormData.value.datas.findIndex(d => d.sourceid == row.fid)
              if (index == -1) {
                relFormData.value.datas.push(transferMedium(row))
              }
            }
          })
        } else {
          relFormData.value.datas = []
        }
      }
      /** 获取选择的图片信息 **/
      const handleSelectedImgIds = (row) => {
        if (props.selectType == 'checkbox') {
          const index = relFormData.value.datas.findIndex(d => d.sourceid == row.fid)
          if (index != -1) {
            relFormData.value.datas.splice(index, 1)
            storageTableRef.value.toggleRowSelection(row, false)
          } else {
            relFormData.value.datas.push(transferMedium(row))
            storageTableRef.value.toggleRowSelection(row, true)
          }
        } else {
          relFormData.value.datas = [transferMedium(row)]
        }
      }
      /** 获取选择的视频列表 **/
      const handleSelectedVideos = (row) => {
        if (props.selectType == 'checkbox') {
          const index = relFormData.value.datas.findIndex(d => d.sourceid == row.fid)
          if (index != -1) {
            relFormData.value.datas.splice(index, 1)
            storageTableRef.value.toggleRowSelection(row, false)
          } else {
            relFormData.value.datas.push(transferMedium(row))
            storageTableRef.value.toggleRowSelection(row, true)
          }
        } else {
          relFormData.value.datas = [transferMedium(row)]
        }
      }
      /** 视频播放 **/
      const handleVideoPlay = (row) => {
        context.emit('handleVideoPlay', row)
      }

      /** 文件上传成功 **/
      const handleUploadSuccess = (response) => {
        if (response.errcode == 0) {
          ElMessage({type: 'success', message: response.msg, duration: 2000})
          getFolderFileList()
        } else {
          ElMessage({type: 'error', message: response.msg, duration: 2000})
        }
      }
      /** 文件上传失败 **/
      const handleUploadError = (err) => {
        ElMessage({type: 'error', message: err, duration: 2000})
      }
      /** 重置路径面包屑导航 **/
      const resetBreadcrumbPath = () => {
        breadcrumbList.value = [
          {
            pid: 0,
            path: '/',
            name: '根目录'
          }
        ]
      }
      /** 重置获取目录下文件列表查询条件 **/
      const resetQueryList = () => {
        queryList.path = '/'
        queryList.type = 5
        queryList.startnum = 1
        queryList.pagenum = 25
        queryList.action = 'getlist'
      }

      /** 获取节目集已关联的介质FID **/
      const handleGetReledMediumFids = () => {
        if (props.mediumtype == 'image') {
          if (props.mediatype == 'media') {
            getMediaReledImageFids({mediaid: relFormData.value.mediaid}).then(response => {
              reledFids.value = response.data
            })
          } else if(props.mediatype == 'series') {
            getSeriesReledImages({seriesid: relFormData.value.seriesid}).then(response => {
              reledFids.value = response.data
            })
          } else if(props.mediatype == 'package') {
            getPackageReledFids({packageid: relFormData.value.packageid}).then(response => {
              reledFids.value = response.data
            })
          }
        } else {
          if (props.mediatype == 'media') {
            getMediaReledVideoFids({mediaid: relFormData.value.mediaid}).then(response => {
              reledFids.value = response.data
            })
          } else if (props.mediatype == 'series') {
            getSeriesReledVideoFids({seriesid: relFormData.value.seriesid}).then(response => {
              reledFids.value = response.data
            })
          } else if (props.mediatype == 'package') {
            getPackageReledVideoFids({packageid: relFormData.value.packageid}).then(response => {
              reledFids.value = response.data
            })
          }
        }
      }
      /** 转换介质信息 **/
      const transferMedium = (row) => {
        let resolvepowerArr = row.resolvepower.split('*')
        let width = resolvepowerArr[0] ? parseInt(resolvepowerArr[0]) : 0
        let height = resolvepowerArr[1] ? parseInt(resolvepowerArr[1]) : 0
        let layout = 'unknown'
        if (width > 0 && height > 0) {
          if (width > height) {
            layout = 'horizontal'
          } else if (width < height) {
            layout = 'vertical'
          } else {
            layout = 'square'
          }
        }
        return {
          groupid: currentGroupid.value,
          name: row.name,
          extends: {
            width: width,
            height: height,
            size: parseInt(row.fsize),
            duration: row.codetime ? parseInt(row.codetime) : 0
          },
          sourceid: row.fid,
          layout: layout,
          playtype: props.mediumtype,
          mimetype: mimeTypeList[row.mimeid],
        }
      }

      const tableRowClassName = ({row, rowIndex}) => {
        row.index = rowIndex
      }
      const handleChangeRadio = (row) => {
        relFormData.value.datas = [transferMedium(row)]
      }

      const audioTableColumn = ref([])
      const handleAudioPlay = (refKey) => {
        Object.keys(audioTableColumn.value).forEach(fid => {
          if (refKey != fid) {
            audioTableColumn.value[fid].audioPause()
          }
        })
      }

      /** 初始化 **/
      const init = () => {
        isRoot.value = true
        if (props.relAction == 'relmedium') {
          handleGetReledMediumFids()
        }
        resetQueryList()
        resetBreadcrumbPath()
        getGroupList()
        getRootFolderList()
      }

      return {
        init,
        selectable,
        tableData,
        isloading,
        breadcrumbList,
        handlerLink,
        formatSize,
        mimeTypeList,
        getStorageImageUrl,
        initialIndex,
        srcList,
        handleClickRow,
        handleSelect,
        handleSelectAll,
        storageTableRef,
        handleVideoPlay,
        isRoot,
        queryList,
        getFolderFileList,
        uploadAction,
        uploadFormData,
        handleUploadSuccess,
        handleUploadError,
        isDisabled,
        tableRowClassName,
        selectedRadioIndex,
        handleChangeRadio,
        getVideoPlayUrl,
        handleAudioPlay,
        audioTableColumn
      }
    }
  }
</script>

<style scoped>

</style>
